/** 调整页面 */
<template>
  <div v-loading="loading" class="view-page p-10px">
    <div class="mb-10px p-6px form-search">
      <jg-form-search
        ref="formSearch"
        :data="form.model"
        :items="form.items"
        :form-config="{
          labelWidth: 120,
          labelPosition: 'left'
        }"
        layout="grid"
        collapse-button
        responsive
        @search="search"
        @reset="search"
      />
    </div>
    <div>
      <jg-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvent" />
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { reactive, ref } from 'vue'
import type { VxeGridInstance } from 'vxe-table'
import { getDenmandViewList } from '@/api/demand'
import { useI18n } from '@/hooks/web/use-i18n'
const { t } = useI18n()
let loadColumn = false
const loading = ref(false)
const xGrid = ref({} as VxeGridInstance)
const form = reactive({
  model: {
    dataSource: '1',
    factNo: 'A155',
    versionNo: '20230609'
  },
  items: [
    {
      prop: 'dataSource',
      label: t('demand.dataSource'),
      component: 'Jg-select',
      attrs: {
        options: [
          { label: t('demand.manualMaintenance'), value: '1' },
          { label: t('demand.accessToData'), value: '2' }
        ]
      }
    },
    {
      prop: 'factNo',
      label: t('demand.factory'),
      required: true,
      component: 'JgInput',
      attrs: {
        selectPopParam: {
          selectParam: { selectCode: 'SAP_T001W_NEW', selectProp: 'FACT_NO' }
        }
      }
    },
    {
      prop: 'versionNo',
      label: t('demand.versions'),
      required: true,
      component: 'JgInput',
      attrs: {
        selectPopParam: {
          selectParam: { selectCode: 'INDEPENDENT_DEMAND_VERSION_NO', selectProp: 'VERSION_NO' }
        }
      }
    },
    {
      prop: 'dataStatus',
      label: t('demand.dataStatus'),
      component: 'Jg-select',
      attrs: {
        options: [
          { label: t('demand.toBeReleased'), value: '1' },
          { label: t('demand.pendingReview'), value: '2' },
          { label: t('demand.toBeAssigned'), value: '4' },
          { label: t('demand.reviewed'), value: '3' }
        ],
        clearable: true,
        placeholder: t('demand.chooseStatus')
      }
    }
    // {
    //   prop: 'date',
    //   label: t('demand.date'),
    //   component: 'el-date-picker',
    //   attrs: {
    //     valueFormat: 'YYYY-MM-DD',
    //     type: 'date',
    //     placeholder: t('demand.selectDate')
    //   }
    // }
  ]
})
const formData = ref()

// 列兼容处理
const getAppendColumns = (
  column: { [x: string]: any; headerName: any; children: any }[],
  width: string | null
) => {
  return column.map(({ headerName, children, ...col }) => {
    const item: any = { ...col, title: headerName }
    if (width) item.width = width
    if (children?.length) {
      item.children = getAppendColumns(children, '100px')
    }
    return item
  })
}
// 列表配置项
const gridOptions = reactive({
  keepSource: true,
  size: 'small',
  height: 600,
  rowStyle({ row }) {
    return row.background
  },
  columnConfig: {
    minWidth: 80,
    resizable: true
  },
  rowConfig: {
    isHover: true
  },

  pagerConfig: {
    pageSize: 10,
    pageSizes: [5, 10, 15, 30, 100]
  },

  toolbarConfig: {
    buttons: [
      { code: 'insert_actived', name: t('demand.add'), status: 'primary' },
      { code: 'delete', name: t('demand.delete'), status: 'primary' },
      { code: 'save', name: t('demand.save'), status: 'primary' },
      { code: 'exportExcel', name: t('demand.export'), status: 'primary' }
    ],
    refresh: false, // 显示刷新按钮
    zoom: true, // 显示全屏按钮
    custom: true // 显示自定义列按钮
  },
  proxyConfig: {
    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
    autoLoad: false,
    props: {
      // 对应响应结果 Promise<{ result: [], page: { total: 100 } }>
      result: 'result', // 配置响应结果列表字段
      total: 'page.total' // 配置响应结果总页数字段
    },
    // 只接收Promise，具体实现自由发挥
    ajax: {
      // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
      query: ({ page, sorts, filters, form, data }) => {
        console.log(11111, page, sorts, filters, form, data)
        const queryParams: any = Object.assign({}, form, formData.value, page)
        console.log(222, queryParams)
        // 处理排序条件
        // const firstSort = sorts[0]
        // if (firstSort) {
        //   queryParams.sort = firstSort.field
        //   queryParams.order = firstSort.order
        // }
        // 处理筛选条件
        // filters.forEach(({ field, values }) => {
        //   queryParams[field] = values.join(',')
        // })
        queryParams.pageNum = queryParams.currentPage
        return getDenmandViewList(queryParams).then((response) => {
          if (!loadColumn) {
            console.log('response.data.columns', response.data.columns)
            gridOptions.columns.push(...getAppendColumns(response.data.columns, null))
            loadColumn = true
          }
          return {
            result: response.data.list,
            page: {
              total: response.data.total
            }
          }
        })
      },
      // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
      delete: () => {},
      // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
      save: () => {}
    }
  },
  columns: [
    { type: 'checkbox', title: '', width: 60, fixed: 'left' },
    {
      field: 'factNo',
      title: t('demand.factory'),
      editRender: {
        name: 'PopSelect',
        attrs: {
          props: { value: 'FACT_NO', label: 'FACT_NO' },
          gridConfig: {
            columns: [
              {
                field: 'FACT_NO',
                title: '工厂编号',
                width: 80
              },
              {
                field: 'FACT_NAME',
                title: '工厂名称'
              },
              {
                field: 'FACT_ADDR',
                title: '工厂地址'
              }
            ]
          },
          options: [
            {
              FACT_ADDR: '辽宁省沈阳市沈北新区沈北路20-3号-6',
              FACT_NO: '0004',
              FACT_NAME: '合肥比亚迪盛世新景汽车销售有限公司',
              WERKS: '0004'
            },
            {
              FACT_ADDR: '深圳市龙岗区葵涌镇延安路比亚迪工业园',
              FACT_NO: '1000',
              FACT_NAME: '比亚迪股份总公司工厂',
              WERKS: '1000'
            },
            {
              FACT_ADDR: '宝龙比亚迪内：正大门直行100米',
              FACT_NO: '1001',
              FACT_NAME: '后勤比亚迪股份工厂',
              WERKS: '1001'
            },
            {
              FACT_ADDR: '宝龙比亚迪内：正大门直行100米',
              FACT_NO: '1002',
              FACT_NAME: '后勤精密制造工厂',
              WERKS: '1002'
            },
            {
              FACT_ADDR: '葵涌镇延安路1号比亚迪工业园 A-6#厂房 2楼',
              FACT_NO: '1003',
              FACT_NAME: '比亚迪半导体股份有限公司后勤微电子工厂',
              WERKS: '1003'
            },
            {
              FACT_ADDR: '深圳市龙岗区葵涌镇延安路比亚迪',
              FACT_NO: '10Z0',
              FACT_NAME: '中研院公共工厂',
              WERKS: '10Z0'
            },
            {
              FACT_ADDR: '深圳市龙岗区葵涌镇延安路比亚迪',
              FACT_NO: '10Z1',
              FACT_NAME: '中研院应用材料工厂',
              WERKS: '10Z1'
            },
            {
              FACT_ADDR: '深圳市龙岗区葵涌镇延安路比亚迪',
              FACT_NO: '10Z2',
              FACT_NAME: '中研院金属材料工厂',
              WERKS: '10Z2'
            },
            {
              FACT_ADDR: '深圳市龙岗区葵涌镇延安路比亚迪',
              FACT_NO: '10Z3',
              FACT_NAME: '中研院导光膜工厂',
              WERKS: '10Z3'
            },
            {
              FACT_ADDR: '深圳市龙岗区葵涌镇延安路比亚迪工业园',
              FACT_NO: '2000',
              FACT_NAME: '一部股份数字能源工厂',
              WERKS: '2000'
            }
          ]
        }
      }
    },
    {
      field: 'planSortRule',
      title: '创建时间',
      width: 160,
      editRender: { name: 'DatePicker', attrs: { valueFormat: 'YYYYMMDD' } }
    },
    {
      field: 'planSortRule',
      title: t('demand.planSortingRules')
    },
    {
      field: 'typeNo',
      title: t('demand.category')
    },
    {
      field: 'matNo',
      title: t('demand.materials')
    },
    {
      field: 'matDesc',
      title: t('demand.materialDescription'),
      editRender: { name: 'Input' }
    },
    {
      field: 'matVersion',
      title: t('demand.materialVersion')
    },
    {
      field: 'beskz',
      title: t('demand.purchaseType')
    },
    {
      field: 'prodVersion',
      title: t('demand.productionVersion')
    },
    {
      field: 'optionBomNo',
      title: t('demand.optionalBOMNumber')
    },
    {
      field: 'unit',
      title: t('demand.unit')
    },
    {
      field: 'dataSource',
      title: t('demand.dataSource')
    },
    {
      field: 'inputFactNo',
      title: t('demand.demandFactory')
    },
    {
      field: 'dataStatus',
      title: t('demand.dataStatus')
    },
    {
      field: 'custName',
      title: t('demand.customerName')
    },
    {
      field: 'projectNo',
      title: t('demand.projects')
    },
    {
      field: 'projectNoName',
      title: t('demand.projectName')
    },

    {
      field: 'parmatNo',
      title: t('demand.upperStageMaterials')
    },
    {
      field: 'warehouse',
      title: t('demand.warehouseGroup')
    },
    {
      field: 'expireDemandNum',
      title: t('demand.expiredRequirements')
    }
  ],
  // 列表编辑配置
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true,
    showIcon: false
  },
  exportConfig: {
    modes: ['current', 'selected']
  },
  checkboxConfig: {
    reserve: true,
    highlight: true,
    range: true
  }
})
// 列表事件
const gridEvent = {
  // 列表pagenation发生变化
  pageChange(val) {
    console.log(12334, val)
    xGrid.value.commitProxy('query')
  },
  proxyQuery() {
    console.log('数据代理查询事件')
  },
  proxyDelete() {
    console.log('数据代理删除事件')
  },
  proxySave() {
    console.log('数据代理保存事件')
  },
  // 按钮点击事件
  toolbarButtonClick({ code, $event }: any) {
    if (code === 'exportExcel') {
      if (!gridOptions?.proxyConfig?.props.total) return
      const checked = xGrid.value.getCheckboxRecords()
      loading.value = true
      if (checked.length) {
        // 只导出勾选的行
        xGrid.value
          .exportData({
            mode: 'selected'
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        // 导出全部
        xGrid.value
          .exportData({
            mode: 'all'
          })
          .finally(() => {
            loading.value = false
          })
      }
    }
  }
}
// 搜索
const search = (data) => {
  console.log('form data:', data)
  if (!data) return
  formData.value = data
  xGrid.value.commitProxy('query', data)
}
</script>

<style lang="scss">
.theme-default-content {
  max-width: 100% !important;
}
.view-page {
  background: #fff;
  .form-search {
    position: relative;
    &::after {
      content: ' ';
      display: block;
      position: absolute;
      left: -10px;
      right: -10px;
      bottom: 0;
      height: 8px;
      padding: 0 10px;
      background: whitesmoke;
    }
  }
}
</style>
